package cn.wyl.org.service.impl;

import cn.wyl.basic.service.impl.BaseServiceImpl;
import cn.wyl.basic.util.PageList;
import cn.wyl.org.domain.Department;
import cn.wyl.org.mapper.DepartmentMapper;
import cn.wyl.org.query.DepartmentQuery;
import cn.wyl.org.service.IDepartmentService;
import org.junit.platform.commons.annotation.Testable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//业务实现类：部门
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        List<Department> departments= departmentMapper.findAll();
        //将所有部门查询出来 - 装到map集合 => 为了方便通过id找部门对象
        HashMap<Long, Department> map = new HashMap<>();
        for (Department department:departments){
            map.put(department.getId(),department);
        }
        List<Department> deptTree = new ArrayList<>();
        //遍历所有部门
        for (Department department:departments){
            if (department.getParent_id() == null){
                //添加到部门树
                deptTree.add(department);
            }else {
                Long parent_id = department.getParent_id();
                //获取父部门对象
                Department parentDepartment = map.get(parent_id);
                if (parentDepartment != null){
                    //将自己状态父部门的children集合中
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }

}
